//
//  Toast.swift
//  YXRSmartDeviceDemo
//
//  Created by run on 2025/1/16.
//

import SwiftUI
import AlertToast

// 显示
func showLoading(_ msg: String? = nil, _ max: TimeInterval = 15) {
    ToastManager.shared.showLoading(max: max)
}

//toast
func showToast(_ msg: String, _ max: TimeInterval = 2.0) {
    ToastManager.shared.showToast(message: msg, duration: max)
}

// 隐藏
func hideLoading() {
    ToastManager.shared.hideLoading()
}

class ToastManager: ObservableObject {
    static let shared = ToastManager() // 单例实例
    
    @Published var isShowing: Bool = false
    @Published var toast: AlertToast? = nil
    
    private var loadingTimeoutTimer: Timer?
    
    private init() {}
    
    /// 显示加载状态的 Toast
    func showLoading(message: String? = nil, max: TimeInterval = 15) {
        toast = AlertToast(displayMode: .alert, type: .loading, title: message)
        isShowing = true
        
        // 设置超时计时器
        loadingTimeoutTimer = Timer.scheduledTimer(withTimeInterval: max, repeats: false) { [weak self] _ in
            self?.hideLoading() // 超时后隐藏 Toast
        }
    }
    
    /// 隐藏加载状态
    func hideLoading() {
        // 停止计时器
        resetLoadingTimer()
        isShowing = false
    }
    
    /// 显示普通 Toast
    func showToast(message: String, subTitle: String? = nil, duration: TimeInterval = 2) {
        // 隐藏当前的 Loading Toast（如果存在）
        hideLoading()
        
        toast = AlertToast(displayMode: .alert, type: .regular, title: message, subTitle: subTitle)
        isShowing = true
        
        // 自动隐藏
        DispatchQueue.main.asyncAfter(deadline: .now() + duration) {
            self.isShowing = false
        }
    }
    
    /// 重置计时器
    private func resetLoadingTimer() {
        loadingTimeoutTimer?.invalidate()
        loadingTimeoutTimer = nil
    }
}


struct ToastModifier: ViewModifier {
    @ObservedObject var toastManager = ToastManager.shared
    
    func body(content: Content) -> some View {
        content
            .toast(isPresenting: $toastManager.isShowing, duration: 15, tapToDismiss: true) {
                toastManager.toast ?? AlertToast(type: .regular, title: "Toast")
            }
    }
}

extension View {
    func withToast() -> some View {
        self.modifier(ToastModifier())
    }
}
